//
//  NetRequestClass.m
//
//
//  Created by apple开发
//
//

#import "NetRequestClass.h"
#import "zlib.h"
#import "AFNetworking.h"
#import "NSString+Utility.h"


@interface NetRequestClass()

@end

@implementation NetRequestClass

#pragma mark - GET请求
+ (void)NetRequestGetWithRequestURL:(NSString *)requestURLString
                      WithParameter:(NSDictionary *)parameter
               WithRetuanValueBlock:(ReturnValueBlock)returnValueBlock
                 WithErrorCodeBlock:(ErrorCodeBlock)errorBlock
{
    
    AFHTTPSessionManager *manager = [self sharedNetworkManager];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",[QYGKeychain token]] forHTTPHeaderField:@"Authorization"];
    
    [manager GET:requestURLString parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        QYLog(@"____________url:%@ \nstr=%@", task.response.URL,str);
        
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        if(response.statusCode >= 200 && response.statusCode < 300){
            NSDictionary *responseObjectDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers |                                                                       NSJSONReadingMutableLeaves error:nil];
            returnValueBlock(responseObjectDict);
        }else{
            NSError *error = [NSError errorWithDomain:@"请求失败" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"请求失败"}];
            [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
            errorBlock(error);
        }
  } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
      if(error.code == -1009){
          [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
      }else{
          NSData *errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
          NSDictionary *serializedData = [NSJSONSerialization JSONObjectWithData: errorData options:kNilOptions error:nil];
          [SVProgressHUD showErrorWithStatus:serializedData[@"message"]];
      }
       errorBlock(error);
  }];
    
}
#pragma mark - Post请求
+ (void)NetRequestPostWithRequestURL:(NSString *)requestURLString
                       WithParameter:(NSDictionary *)parameter
                WithReturnValutBlock:(ReturnValueBlock)returnValueBlock
                  WithErrorCodeBlock:(ErrorCodeBlock)errorCodeBlock
{
    AFHTTPSessionManager *manager = [self sharedNetworkManager];
    
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",[QYGKeychain token]] forHTTPHeaderField:@"Authorization"];
    
//    NSString *sign = [self makeSignWithParameter:parameter];
//    NSMutableDictionary *dict = [[self prepareParametersWith:parameter] mutableCopy];
//    [dict setObject:sign forKey:@"sign"];
    
    [manager POST:requestURLString parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
                QYLog(@"____________url:%@ \nstr=%@", task.response.URL,str);
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        if(response.statusCode >= 200 && response.statusCode <= 300){
            
             NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers |                                                                       NSJSONReadingMutableLeaves error:nil];
            returnValueBlock(responseDic);
        }else{
            NSError *error = [NSError errorWithDomain:@"请求失败" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"请求失败"}];
            [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
            errorCodeBlock(error);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if(error.code == -1009){
            [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
        }else{
            NSData *errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
            NSDictionary *serializedData = [NSJSONSerialization JSONObjectWithData: errorData options:kNilOptions error:nil];
            [SVProgressHUD showErrorWithStatus:serializedData[@"message"]];
        }
         errorCodeBlock(error);
}];
    

}


// 取消所有请求
+ (void)cancelOperations
{
    [[[self sharedNetworkManager] operationQueue] cancelAllOperations];
}
+ (AFHTTPSessionManager *)sharedNetworkManager{
    static dispatch_once_t onceToken;
    static AFHTTPSessionManager *manager;
    dispatch_once(&onceToken, ^{
        manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:TEST_HOST]];
        
        manager.requestSerializer.timeoutInterval = 60;
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];//AFJSONRequestSerializer
        [manager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"X-App-Client"];
        [manager.requestSerializer setValue:X_PRODUCT_VERSION forHTTPHeaderField:@"X-Product-Version"];
        //设置请求内容的类型
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/plain", nil];
    });
    return manager;
}

+ (BOOL)NetWorkReachability {
    __block BOOL netState = NO;
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"status -----%ld", (long)status);
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
                netState = YES;
                break;
            case AFNetworkReachabilityStatusNotReachable:
                netState = NO;
                break;
            default:
                break;
        }
    }];
    [mgr startMonitoring];
    return netState;
}
+ (BOOL)NetWorkReachabilityWithURLString:(NSString *)strUrl {
    __block BOOL netState = NO;
    NSURL *baseURL = [NSURL URLWithString:strUrl];
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
    NSOperationQueue *operationQueue = manager.operationQueue;
    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [operationQueue setSuspended:NO];
                netState = YES;
                break;
            case AFNetworkReachabilityStatusNotReachable:
                netState = NO;
                break;
            default:
                [operationQueue setSuspended:YES];
                break;
        }
    }];
    [manager.reachabilityManager startMonitoring];
    return netState;
}


#pragma mark - 内部方法


+ (NSString *)sortParameterStringWithParameter:(NSDictionary *)parameter {
    
    NSDictionary *dict = [self prepareParametersWith:parameter];
    NSArray *array = [[dict allKeys]
                      sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    __block NSString *string = @"";
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        string = [string stringByAppendingString:[NSString stringWithFormat:@"%@%@", obj, dict[obj]]];
        
    }];
    return string;
}
+ (NSString *)makeSignWithParameter:(NSDictionary *)parameter {
    
    //    NSString *partnerSecret = @"c64QSrIOaJ5764D9e64084D1b0dE549";
    NSString *partnerSecret = @"b955f0a62c4d56319b976ef24a05bb9f";
    NSString *sign = @"";
    
    //parameter 需要排序
    NSString *parameterString = [self sortParameterStringWithParameter:parameter];
    sign = [sign stringByAppendingString:parameterString];
    sign = [sign md5];
    sign = [sign stringByAppendingString:partnerSecret];
    return [sign md5];
}
+ (NSMutableDictionary *)prepareParametersWith:(NSDictionary *)parameter {
    parameter = !parameter ? @{} : parameter;
    NSMutableDictionary *dict = [parameter mutableCopy];
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a];//转为字符型
    
    [dict setObject:timeString forKey:@"ts"];
    [dict setObject:@"qyguo" forKey:@"platform"];
    return dict;
}

/*
 + (void)downloadFileWithRequestURL:(NSString *)requestURLString
 complete:(void(^)(BOOL))complete
 {
 
 //1.创建会话管理者
 
 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
 
 [manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
 [manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
 
 //    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",Download_Data_Url,requestURLString]];
 
 NSURLRequest *request = [NSURLRequest requestWithURL:url];
 
 NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
 
 float progress = 1.0 *downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
 //        [SVProgressHUD showProgress:progress status:@"正在下载..."];
 
 
 } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
 NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
 
 DDLog(@"targetPath:%@",targetPath);
 
 DDLog(@"fullPath:%@",fullPath);
 
 //        [SVProgressHUD dismiss];
 
 return [NSURL fileURLWithPath:fullPath];
 
 } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
 
 if(error)
 {
 complete(NO);
 return;
 }
 NSString *zipPath = [filePath path];
 
 NSData *fileData = [NSData dataWithContentsOfFile:zipPath];
 
 NSData *myData = [self gzipUncompress:fileData];
 // 将数据移植到数据库
 [self setSQLDataWithStr:myData complete:^(BOOL isSuccess) {
 complete(isSuccess);
 }];
 
 }];
 
 //3.执行Task
 
 [download resume];
 
 }
 
 */


@end
